import datetime
import logging
import os
import time
import random
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import py.datamodel
import simplejson as JSON

class Viewer(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-Type'] = 'text/html'
       
        sos_identifier = self.request.cookies.get("sos_identifier")
        if not sos_identifier:
            sos_identifier = str(random.random()) + str(random.random())
        
        self.response.headers.add_header("Set-Cookie", "sos_identifier=" + str(sos_identifier))

        owner = self.request.get("owner")
        viewer = self.request.get("viewer")
        container = "orkut"
        sessionId = ""
  
        ownerId = container + "-" + JSON.loads(owner)["id"]      
        knownVisitor = False
        if viewer == "null":
            viewerId = "null"
        else:
            viewerId = container + "-" + JSON.loads(viewer)["id"]
            knownVisitor = True
        if knownVisitor == True:
            visitCount = py.datamodel.Visit()
            visitCount.owner = owner
            visitCount.ownerId = ownerId;
            visitCount.viewer = viewer
            visitCount.viewerId = viewerId
            visitCount.cookie = sos_identifier
            visitCount.sessionId = str(random.random())
            sessionId = visitCount.sessionId
            visitCount.ip = self.request.remote_addr
            visitCount.param = self.request.get("browser");
            visitCount.enterTime = datetime.datetime.now()
            visitCount.exitTime = datetime.datetime.now() + datetime.timedelta(seconds=30)
            visitCount.put()
        else:
            UnknownVisit = py.datamodel.UnknownVisit()
            UnknownVisit.owner = owner
            UnknownVisit.ownerId = ownerId;
            UnknownVisit.cookie = sos_identifier
            UnknownVisit.sessionId = str(random.random())
            sessionId = UnknownVisit.sessionId
            UnknownVisit.ip = self.request.remote_addr
            UnknownVisit.param = self.request.get("browser");
            UnknownVisit.enterTime = datetime.datetime.now()
            UnknownVisit.exitTime = datetime.datetime.now() + datetime.timedelta(seconds=30)
            UnknownVisit.put()

        preferences = db.Query(py.datamodel.Preferences)
        preferences = preferences.filter("owner =", ownerId)
        if preferences.count() == 0:
            userPreferences = py.datamodel.Preferences()
            userPreferences.owner = ownerId
            userPreferences.feedPrefs = "UserCount"
            userPreferences.totalCount = 1
            userPreferences.counters = '{"knownVisitors" : 0}';
            userPreferences.put();
        else: 
            ownerPreference = preferences.get()
            ownerPreference.totalCount += 1
            if knownVisitor == True:
                ownerPreferenceJSON = JSON.loads(ownerPreference.counters)
                if "knownVisitors" in ownerPreferenceJSON:
                    ownerPreferenceJSON["knownVisitors"] += 1
                else:
                    ownerPreferenceJSON["knownVisitors"] = 1
                ownerPreference.counters = JSON.dumps(ownerPreferenceJSON)
            ownerPreference.put()

        # Assuming that the sneak-o-scope will always exist and will always have valid value
        # Hence, skipping all code for bootstrappting record for this user
        preferences = db.Query(py.datamodel.Preferences)
        preferences = preferences.filter("owner =", "sneakoscope")
        ownerPreference = preferences.get()
        ownerPreference.totalCount += 1
        if knownVisitor == True:
            ownerPreferenceJSON = JSON.loads(ownerPreference.counters)
            ownerPreferenceJSON["knownVisitors"] += 1
            ownerPreference.counters = JSON.dumps(ownerPreferenceJSON)
        ownerPreference.put()

        template_values = {}
        template_values["owner"] = owner
        template_values["ownerId"] = ownerId
        template_values["sessionId"] = sessionId
        template_values["container"] = container

        if self.request.get("view") == "canvas":
            path = os.path.join(os.path.dirname(__file__), "../templates/viewer-canvas.html")
        else:
            path = os.path.join(os.path.dirname(__file__), "../templates/viewer-profile.html")
        self.response.out.write(template.render(path, template_values))

class ViewerTime(webapp.RequestHandler):
    def post(self):
        
        loadTime = self.request.get("loadTime")
        unloadTime = self.request.get("unloadTime")
        sessionId = self.request.get("sessionId")
        
        # we don't really care about the date that the client sends us, we simply use server time
        query = db.Query(py.datamodel.Visit)
        query.filter("sessionId =", sessionId)
        visit = query.get()
        if query.count() == 0:
            query = db.Query(py.datamodel.UnknownVisit)
            query.filter("sessionId =", sessionId)    
            visit = query.get()
            
        if visit != None:
            if unloadTime == "null":
                visit.enterTime = datetime.datetime.now()
                visit.exitTime = datetime.datetime.now()
            if loadTime == "null":
                visit.exitTime = datetime.datetime.now()
            visit.put()
            self.response.out.write("Exit time recorded")
        else:
            logging.info("Could not find session Id %s" % sessionId)

    def get(self):
        self.post()
        
        
if __name__ == '__main__':
  application = webapp.WSGIApplication(
      [
        ('/viewer', Viewer),
        ('/viewer/time', ViewerTime)
      ],
      debug=True)

  wsgiref.handlers.CGIHandler().run(application)